/**
 * 高值耗材采购模块，提供医疗服务编辑页面初始化组件功能
 * 
 * @Date: 2016-1-25
 * @author: Jackson wang
 * @version: 1.0
 * @since: 1.0
 */

define(	["jquery", "sysmanMain", "msgServ", "flowInit", "datagridServ",
				"panelUtil", "uploadfiles"], function($, sysmanMain, msgServ,
				flowInit, datagridServ, panelUtil, uploadfiles) {

			'use strict';
			var _typeUrl = '/dictionary/getTree.action', 
			_rootpath, 
			el_width = 300, 
			el_big_width = 674, 
			window_width = 900, 
			window_height = 700, 
			
			//业务编码
			_bizcode = 'oaLeaver',
			rootid = 'panel-oa-leaver', 
			window_id = '', 
			edit_window_id = 'oa-leaver-win',
			editIndex

			var public_method = {

				/**
				 * 初始化新增页面
				 * 
				 * @param _options.record
				 *            列表选中行
				 * @param _options.form
				 *            页面form对象
				 * @param _options.rootid
				 *            页面根节点id
				 * @param _options.flowStateSelector
				 *            流程状态字段选择器
				 */
				initElement : function(_options) {

					if (window.console) {
						console.info(' leaver init loaded and startting ...')
					}
					private_method.initFileList();
					var queryUrl = '';
					$('#' + rootid + ' #dg-inner-leaver').datagrid({
								url : queryUrl,
								height : 100,
								onClickCell : private_method.editCell,
								columns : [[{
											field : 'ck',
											checkbox : "true"
										}, {
											field : 'name',
											title : '耗材名称',
											halign : 'center',
											width : 30,
											editor : 'text'
										}, {
											field : 'activityName',
											title : '规格型号',
											width : 30,
											align : 'center',
											halign : 'center',
											editor : 'text'
										}, {
											field : 'activityType',
											title : '计量单位',
											width : 30,
											align : 'center',
											halign : 'center',
											editor : 'text'
										}, {
											field : 'sortedid',
											title : '采购数量',
											width : 30,
											align : 'center',
											halign : 'center',
											editor : 'text'
										}, {
											field : 'bizname',
											title : '进货价格',
											width : 30,
											align : 'center',
											halign : 'center',
											editor : 'text'
										}, {
											field : 'fullBizcode',
											title : '流水号',
											width : 30,
											align : 'right',
											halign : 'center',
											editor : 'text'
										}, {
											field : 'activityConfig',
											title : '供应商',
											width : 100,
											align : 'right',
											halign : 'center',
											editor : 'text'
										}]],
								rownumbers : true,
								animate : true,
								striped : true,
								singleSelect : true,
								border : true,
								idField : 'id',
								fitColumns : true,
								toolbar : rootid + 'inner-table-leaver'
							})

				},
				closeWindow : function() {
					$('#' + rootid + ' a.inner-table-btn').unbind('click');
					$('#' + rootid).empty()
					var _moduleConfig = sysmanMain.getCurrentModuConfig();
					_moduleConfig.initParam = {
						editable : true
					};
					sysmanMain.setCurrentModuConfig(_moduleConfig);
				},
				/**
				 * @param _options.rootid
				 * @param _options.conditionSelector
				 * @param _options.
				 */
				initList : function(_options) {
					private_method.initCondition(_options)
				},
				/**
				 * @param _options.record
				 */
				buttonExtends : function() {
					var leaver_inner_table = $('#' + rootid
							+ ' #dg-inner-leaver')
					return {
						'耗材清单' : private_method.detailInfo,
						'耗材添加' : function() {
							$(leaver_inner_table).datagrid('appendRow', {})
						},
						'附件' : function() {
							private_method.uploadInit()
						},
						'返回' : function() {
							console.info("I've got the return button!!!")
							private_method.changePanel({
										classType : 'edit-panel'
									})
							private_method.initFileList();
						},
						'上传' : function() {
							console.info("I've got the upload button!!!")
							private_method.upload()
						},
						'删除' : function() {
							console.info("I've got the upload button!!!")
							private_method.delFile()
						},
						'流程图' : function() {
							private_method.changePanel({
										classType : 'historicalDiagram-panel'
									})
						},
						'流程节点' : function() {
							private_method.changePanel({
										classType : 'historical-panel'
									})
							//flowInit.initList(_options)
						},
						'耗材删除' : function() {
							var record = $(leaver_inner_table)
									.datagrid('getSelected');
							if (record) {
								var rowindex = $(leaver_inner_table).datagrid(
										'getRowIndex', record);

								$(leaver_inner_table).datagrid('deleteRow',
										rowindex);
							} else {
								msgServ.Msgslide('请选择删除的记录');
							}
						}
					}
				},

				reCreateField : function(_options) {
					private_method.reCreateField(_options)
				},
				rowDblClick : function(index, row) {
					private_method.rowDblClick(index, row)
				}

			}

			var private_method = {
				editCell : function(index, field, value) {
					if (window.console)
						console.info(' editCell fired ...')
					var leaver_inner_table = $('#' + rootid
							+ ' #dg-inner-leaver')
					if (editIndex > -1 && (editIndex != index)) {
						$(leaver_inner_table).datagrid('acceptChanges');
						$(leaver_inner_table).datagrid('endEdit', editIndex);
					}

					$(leaver_inner_table).datagrid('beginEdit', index);
					editIndex = index
				},
				initFileList : function() {
					var el = $('#' + edit_window_id
							+ ' form.main-form div.fileList')
					var _idEl = $('#' + edit_window_id + ' form.main-form #id')
					var uploadListurl = '/upload/query/getInitListDomain.action'
					var _moduleConfig = sysmanMain.getCurrentModuConfig();
					if (!_idEl.val()) {
						return;
					}
					var parm = {
						condition : {
							bizno : _idEl.val(),
							bizcode : _bizcode
						}
					}
					$.ajax({
								url : '/' + sysmanMain.getRootPath()
										+ uploadListurl,
								type : 'post',
								async : false,
								data : parm,
								success : function(result) {
									var _aParam = {
										target : el,
										data : result
									}

									private_method.appendList(_aParam)
								},
								failure : function(result) {
									if (window.console) {
										console.log('ajax call failured ...')
									}
								}
							})
				},
				appendList : function(_options) {
					if (_options.target && _options.data) {
						$(_options.target).empty();
						var _html = '点击名字下载';
						$.each(_options.data.rows, function(i, e) {
							console.info("got one");
							_html += '<span style = "cursor:pointer" onmouseover="font color="#0000FF"" onmouseout="font color="#FFFFFF"" class = "'
									+ 'fileDownBut'
									+ '"'
									+ 'fileId = "'
									+ e.id
									+ '">' + e.filename + '</span>';
						})
						// private_method.changeStyle()
						$(_options.target).append(_html)
						$(".fileDownBut").unbind('click')
						$(".fileDownBut").bind('click',
								private_method.fileDownload)

					}
				},
				changeStyle : function() {
					$(".fileDownBut").live({
								mouseover : function() {
									$(this).css("font-color", "blue");
								},
								mouseout : function() {
									$(this).css("font-color", "black");
								}
							})
				},

				fileDownload : function(e) {
					if (e) {
						var tpObj = e.currentTarget
						private_method.downloadfile($(tpObj).attr('fileId'));
					}
				},
				downloadfile : function(id) {
					if (window.console) {
						console.log('download file fired ')
					}
					var _url = '/' + sysmanMain.getRootPath()
							+ '/upload/downloadFileTest.action'
					var form = $("<form>");
					form.attr('style', 'display:none');
					form.attr('target', '');
					form.attr('method', 'post');
					form.attr('action', _url);
					var input1 = $("<input>");
					input1.attr('type', 'hidden')
					input1.attr('name', 'id')
					input1.attr('value', id);
					$('body').append(form);
					$(form).append(input1);

					form.submit();
					form.remove();

				},
				uploadInit : function() {
					var _moduleConfig = sysmanMain.getCurrentModuConfig();

					var $edit_window = $('#' + edit_window_id);
					var isSaved = false, _id
					var _idEl = $('#' + edit_window_id + ' form.main-form #id')
					if (_idEl.length == 1) {
						_id = $(_idEl).val()
						if (_id) {
							isSaved = true
						}
					}

					if (!isSaved) {
						msgServ.Msgslide('保存后才能上传附件');
						return
					}
					this.uploadInitList({
								_moduleConfig : _moduleConfig
							});
					private_method.changePanel({
								classType : 'upload-panel'
							})
					if (_moduleConfig.bizcode && _id) {
						this.uploadInitRel({
									_moduleConfig : _moduleConfig
								});
					}
				},

				upload : function() {
					uploadfiles.upload()
				},
				delFile : function() {
					uploadfiles.del({
								biztableid : edit_window_id
										+ ' div.table-archive',
								rootPath : '/' + sysmanMain.getRootPath()
							})
				},
				uploadInitList : function(_options) {
					var _idEl = $('#' + edit_window_id + ' form.main-form #id')
					uploadfiles.initList({
						data : {
							bizno : _idEl.val(),
							bizcode : _bizcode
						},
						rootPath : '/' + sysmanMain.getRootPath(),
						biztableid : edit_window_id
								+ ' div.upload-panel div.table-archive',
						toolbarid : edit_window_id
								+ ' div.upload-panel div.archive-btn a.file_upload_btn'

					})
				},

				uploadInitRel : function(_options) {
					var _idEl = $('#' + edit_window_id + ' form.main-form #id')
					uploadfiles.init({
						data : {
							bizno : _idEl.val(),
							bizcode : _bizcode
						},
						queue_id : edit_window_id
								+ ' div.upload-panel form.upload-form #queue',
						file_id : edit_window_id
								+ ' div.upload-panel form.upload-form #file_upload',
						rootPath : '/' + sysmanMain.getRootPath(),
						rootid : edit_window_id

					})
				},

				changePanel : function(_options) {
					var _moduleConfig = sysmanMain.getCurrentModuConfig();
					var tep = $('#' + edit_window_id + ' div.toggle-panel')
					console.info("run, saw?")
					tep.panel('close')
					if (tep.length > 0) {
						tep.panel('close')
						console.info("here all closed")
					}

					// var hd =
					// if(_options && _options.length > 0 && _options.classType
					// && _options.classType.length > 0){
					tep = $('#' + edit_window_id + '  div.'
							+ _options.classType)
					tep.panel('open')
					console.info("here " + _options.classType + " closed")
					// }
				},
				rowDblClick : function(index, row) {

					var editWindow = 'oa-leaver-win';
					var _param = {}
					var _moduleConfig = sysmanMain.getCurrentModuConfig();
					if (!_moduleConfig) {
						_moduleConfig = {}
					}

					var flow_state_el = $('#' + rootid
							+ ' form.condition-form #flow_state')
					var flow_state_value = $(flow_state_el)
							.combobox('getValue')
					if (flow_state_value && flow_state_value === 'finished') {
						_param.editable = false
					} else {
						_param.editable = true
					}
					_moduleConfig.initParam = _param
					sysmanMain.setCurrentModuConfig(_moduleConfig)

					var $grid = $('#' + rootid + " table.dg-list");
					var $edit_window = $('#' + editWindow);
					var _url = '/' + sysmanMain.getRootPath()
							+ '/oaLeaver/query/editPage.action';
					var _dgparam = {
						grid : $grid,
						window : $edit_window,
						href : _url,
						width : window_width,
						height : window_height,
						flag : true,
						existCheckElement : 'form'
					}

					_dgparam.onClose = public_method.closeWindow

					datagridServ.windowEdit(_dgparam);
				},
				/**
				 * 初始化条件查询框
				 * 
				 * @param _options.rootid
				 *            窗口根节点id
				 * @param _options.conditionSelector
				 *            条件框节点选择器
				 */
				initCondition : function(_options) {
					if (window.console) {
						console.info('leaver init loaded and starting...')
					}

					flowInit.initList(_options)
				},
				detailInfo : function() {
					if (window.console) {
						console.info('show detail loaded...')
					}

					var _config = {}
					// 查找耗材清单panel
					var innerpanelElement = $('#' + rootid
							+ ' div.inner-table-panel')

					var _inpatientno
					if (innerpanelElement.length > 0) {
						// 判断panel状态
						var isopen = panelUtil.getPanelState({
									target : innerpanelElement
								})
						if (isopen) {
							$(innerpanelElement).panel('close')
						} else {
							$(innerpanelElement).panel('open')
						}
					}

				},
				/**
				 * 更新质询子类信息
				 * 
				 * @param _options.form
				 * @param _options.record
				 * @param _options.target
				 */
				changeSubItem : function(_options) {
					var _subSelect = $(_options.form)
							.find('#inquiry_item_subcode')
					$(_subSelect).combobox({
						textField : 'name',
						valueField : 'id',
						readonly : false,
						url : _rootpath + '/dictionary/getTree.action?id='
								+ _options.record.id,
						onSelect : function(record) {
							var _item = $(_options.form)
									.find('#inquiry_item_sub')
							$(_item).val(record.text)
						}
					})
				},
			
				reCreateField : function(_options) {
					if (window.console) {
						console
								.info(' leaver reCreateField loaded and startting ...')
					}
					var data = _options.data
					var $form = _options.form
					_rootpath = '/' + sysmanMain.getRootPath()

					var normal_param = {
						required : true,
						editable : true
					}
					var normal_width_param = $.extend({}, normal_param, {
								width : el_width
							})
					var big_width_param = $.extend({}, normal_param, {
								width : el_big_width,
								multiline : true,
								height : 50
							})
					var deptQueryUrl = '/department/query/getTreeList.action'
					var selectedRecord = $('#panel-oa-leaver table.dg-list')
							.datagrid('getSelected')
					var fields = data.editFilter.enabled.split(',')
					if (fields && (fields.length > 0)) {

						for (var i = 0; i < fields.length; i++) {
							var _el = $($form).find('#' + fields[i])
							switch (fields[i]) {
								case 'apply_name' :
									$(_el).textbox(normal_width_param)
									break;
								case 'inquiry_date' :
									$(_el).datebox($.extend({
												readonly : false
											}, normal_width_param))
									if (selectedRecord
											&& selectedRecord.inquiry_date) {
										$(_el).datebox('setValue',
												selectedRecord.inquiry_date)
									}
									break;
								case 'apply_deptname' :
									$(_el).textbox(big_width_param)
									break;
								case 'vac_category' :
									$(_el).textbox(big_width_param)
									break;
								case 'decide_content' :
									$(_el).textbox(big_width_param)
									break;

								case 'affirm_content' :
									$(_el).textbox(big_width_param)
									break;
								case 'patient_id' :
									$(_el).textbox({
										width : el_width,
										required : true,
										readonly : false,
										onClickButton : function(data) {
											var $dept_window = $('#win-dept-patient');

											$($dept_window).attr('callback-id',
													'oa-leaver-win #bizid')
											$($dept_window)
													.attr(
															'callback-patient_id',
															'oa-leaver-win #patient_id')
											$($dept_window).attr(
													'callback-doct_name',
													'oa-leaver-win #doct_name')
											$($dept_window).attr(
													'callback-doct_id',
													'oa-leaver-win #doct_id')
											$($dept_window)
													.attr(
															'callback-doct_depart_name',
															'oa-leaver-win #doct_depart_name')
											$($dept_window)
													.attr(
															'callback-doct_depart_code',
															'oa-leaver-win #doct_depart_code')
											$($dept_window)
													.attr(
															'callback-patient_name',
															'oa-leaver-win #patient_name')
											sysmanMain.deptPatientSelect()
										}
									})
									break;
								case 'inquiry_item_code' :
									var _mainSelect = $(_options.form)
											.find('#inquiry_item_code')
									$(_mainSelect).combobox({
										width : el_width,
										required : true,
										readonly : false,
										textField : 'name',
										valueField : 'id',
										url : _rootpath
												+ '/dictionary/getTree.action?id='
												+ 4,
										onSelect : function(record) {
											var _item = $(_options.form)
													.find('#inquiry_item')
											$(_item).val(record.text)
											private_method.changeSubItem({
														form : _options.form,
														record : record
													})
										},
										onLoadSuccess : function() {
											if (selectedRecord
													&& selectedRecord.inquiry_item_code) {
												$(_mainSelect)
														.combobox(
																'select',
																selectedRecord.inquiry_item_code)
												private_method.changeSubItem({
													form : _options.form,
													record : {
														id : selectedRecord.inquiry_item_code
													}
												})
											}
										}
									})

									break;
								case 'decide_result_code' :
									// 裁决意见
									var _decideSelect = $(_options.form)
											.find('#decide_result_code')
									$(_decideSelect).combobox({
										width : el_width,
										required : true,
										readonly : false,
										textField : 'name',
										valueField : 'id',
										url : _rootpath
												+ '/dictionary/getTree.action?id='
												+ 106,
										onSelect : function(record) {
											var _item = $(_options.form)
													.find('#decide_result')
											$(_item).val(record.name)

											var $username = $(_options.form)
													.find('#decide_name')
											var $userid = $(_options.form)
													.find('#decide_id')

											var curUser = sysmanMain
													.getCurrentUser()
											$($username).textbox('setValue',
													curUser.name)
											$($userid).val(curUser.id)
										},
										onLoadSuccess : function() {
											if (selectedRecord
													&& selectedRecord.decide_result_code) {
												$(_decideSelect)
														.combobox(
																'select',
																selectedRecord.decide_result_code)
											}
										}
									})

									break;
								case 'affirm_result_code' :
									// 认定意见
									var _confirmSelect = $(_options.form)
											.find('#affirm_result_code')
									$(_confirmSelect).combobox({
										width : el_width,
										required : true,
										readonly : false,
										textField : 'name',
										valueField : 'id',
										url : _rootpath
												+ '/dictionary/getTree.action?id='
												+ 112,
										onSelect : function(record) {
											var _item = $(_options.form)
													.find('#affirm_result')
											$(_item).val(record.name)

											var $username = $(_options.form)
													.find('#affirm_name')
											var $userid = $(_options.form)
													.find('#affirm_id')

											var curUser = sysmanMain
													.getCurrentUser()
											$($username).textbox('setValue',
													curUser.name)
											$($userid).val(curUser.id)
										},
										onLoadSuccess : function() {
											if (selectedRecord
													&& selectedRecord.affirm_result_code) {
												$(_confirmSelect)
														.combobox(
																'select',
																selectedRecord.affirm_result_code)
											}
										}
									})

									break;
							}

						}
						// $($form).form('enableValidation').form('validate')
					}
					

				}

			}

			return public_method;

		})